package com.tbit.main.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.tbit.common.constant.MethodEnum;
import com.tbit.common.constant.ModuleEnum;
import com.tbit.common.utils.IpUtil;
import com.tbit.main.common.JsonResult;
import com.tbit.main.constant.OperateLog;
import com.tbit.main.constant.*;
import com.tbit.main.exception.BaseException;
import com.tbit.main.pojo.*;
import com.tbit.main.service.*;
import com.tbit.main.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 账号
 *
 * @author Leon
 * 2020年2月4日 下午7:56:48
 */
@Slf4j
@RestController
@RequestMapping("/accountUser")
public class AccountUserController {
    @Autowired
    private LoginLogService loginLogServie;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private AccountService accountService;
    @Autowired
    private AccountUserService accountUserService;
    @Autowired
    private GeoreGionService georeGionService;
    @Autowired
    private RoleMenuService roleMenuService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private RoleConfigService RoleConfigService;
    @Autowired
    private AccountUserFreeLoginService freeLoginService;

    /**
     * 登录
     */
    @RequestMapping("/login")
    public JsonResult login(String country, String phone, String authCode, String lang,
                            Integer brandId, HttpServletRequest request) {
        /* 校验 */
        Assert.hasLength(phone, "AccountUser.phone.notNull");
        Assert.hasLength(authCode, "System.authCode.notNull");

        /** 国家代码 */
        if (StrUtil.isBlank(country)) {
            country = "86";
        }

        /** 语言 */
        if (StrUtil.isBlank(lang)) {
            lang = "zh";
        }

        Locale locale = new Locale("en", "US");
        if ("zh".equalsIgnoreCase(lang)) {
            locale = new Locale("zh", "CN");
        } else if ("hk".equalsIgnoreCase(lang)) {
            locale = new Locale("zh", "HK");
        }
        request.getSession().setAttribute(SessionLocaleResolver.LOCALE_SESSION_ATTRIBUTE_NAME, locale);

        /**账号是否存在*/
        AccountUser accountUser = accountUserService.getByPhone(new AccountUser(country, phone, brandId));
        if (accountUser == null) {
            throw new BaseException("AccountUser.notExist");
        }
        /*设置是否需要提示设置密码*/
        accountUser.setHasPassword(StrUtil.isBlank(accountUser.getPassword()) ? 0 : 1);

        /**判断账号是否过期*/
        if (accountUser.getExpireDate() != null) {
            if (DateTimeUtil.isBeforeToday(accountUser.getExpireDate())) {
                throw new BaseException("AccountUser.user.expire");
            }
        }

        /**判断短信是否存在*/
        String SMSError = redisService.get(RedisConstant.SMS_MAIN_ERROR + phone);
        if (SMSError != null) {
            throw new BaseException("SMS.ERROR.CODE");
        }
        String totpCode = null;
        String preTOTPCode = null;
        try {
            //兼容六位和四位超级验证码的情况
            if (authCode.length() > 4) {
                //当前时间的动态口令
                totpCode = GoogleAuthenticatorUtils.getTOTPCode(SysConstant.SUPER_PASSWORD_AUTH_SECRET_PLUS, SysConstant.SUPER_PASSWORD_AUTH_DIGITS_PLUS, Integer.parseInt(SysConstant.SUPER_PASSWORD_AUTH_EXPIRE_PLUS));
                //最近刚过期的动态口令
                preTOTPCode = GoogleAuthenticatorUtils.getPreTOTPCode(SysConstant.SUPER_PASSWORD_AUTH_SECRET_PLUS, SysConstant.SUPER_PASSWORD_AUTH_DIGITS_PLUS, Integer.parseInt(SysConstant.SUPER_PASSWORD_AUTH_EXPIRE_PLUS));
            } else {
                //当前时间的动态口令
                totpCode = GoogleAuthenticatorUtils.getTOTPCode(SysConstant.SUPER_PASSWORD_AUTH_SECRET, SysConstant.SUPER_PASSWORD_AUTH_DIGITS, Integer.parseInt(SysConstant.SUPER_PASSWORD_AUTH_EXPIRE));
                //最近刚过期的动态口令
                preTOTPCode = GoogleAuthenticatorUtils.getPreTOTPCode(SysConstant.SUPER_PASSWORD_AUTH_SECRET, SysConstant.SUPER_PASSWORD_AUTH_DIGITS, Integer.parseInt(SysConstant.SUPER_PASSWORD_AUTH_EXPIRE));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        /**验证码错误限制*/
        if (!authCode.equals(SysConstant.SUPER_SMSCODE) && !authCode.equals(totpCode) && !authCode.equals(preTOTPCode)) {
            String authCodeCache = SystemData.phoneAuthCodeMap.get(phone);
            if (authCodeCache == null || !authCodeCache.equals(authCode)) {
                String errorCount = redisService.get(RedisConstant.SMS_MAIN + phone);
                if (errorCount == null) {
                    redisService.add(RedisConstant.SMS_MAIN + phone, "1", 1800);
                } else {
                    int error = Integer.parseInt(errorCount);
                    if (error == 2) {
                        redisService.del(RedisConstant.SMS_MAIN + phone);
                        redisService.add(RedisConstant.SMS_MAIN_ERROR + phone, System.currentTimeMillis() + "", 600);
                    } else {
                        redisService.add(RedisConstant.SMS_MAIN + phone, "2");
                    }
                }
                throw new BaseException("System.authCode.error");
            }
        }

        /**账号类型转换*/
        //品牌、加盟商、区域代理商
        if (accountUser.getSubRoleType() == 0) {
            accountUser.setAccountUserType(accountUser.getAccountType());
            //运维管理员
        } else if (accountUser.getSubRoleType() == 1) {
            accountUser.setAccountUserType(UserConstant.ACCOUNT_MAINTAIN_MANAGER);
            //运维人员
        } else if (accountUser.getSubRoleType() == 2) {
            accountUser.setAccountUserType(UserConstant.ACCOUNT_MAINTAIN);
        } else {
            accountUser.setAccountUserType(accountUser.getSubRoleType());
        }


        /**判断登录权限*/
        Integer accountUserType = accountUser.getAccountUserType();
        Role role = roleService.getRoleId(accountUserType);
        if (!role.getLogin().equals(1) && !role.getLogin().equals(2)) {
            throw new BaseException("System.login.limit");
        }
        accountUser.setRole(role);
        List<RoleConfig> roleConfigs = RoleConfigService.getRoleId(accountUserType);
        accountUser.setRoleConfig(roleConfigs);

        /** 获取运营区域信息 */
        List<Account> accounts = new ArrayList<>();
        // 品牌
        if (accountService.getCountHolderAgent(accountUser.getAccountUserId()) > 0) {
            accounts = accountService.getHolderAgent(accountUser.getAccountUserId());
        } else if ((accountUserType.equals(UserConstant.ACCOUNT_BRAND) ||
                accountUser.getRole().getRoleLevel().equals(UserConstant.ACCOUNT_BRAND))
                && !accountUserType.equals(UserConstant.ACCOUNT_FRANCHISEE)
                && !accountUserType.equals(UserConstant.ACCOUNT_ADOPT)) {
            /** 加载品牌下的所有运营区域 */
            accounts = accountService.getBrandAgent(accountUser.getAccountId());
        }
        // 加盟商
        else if ((accountUserType.equals(UserConstant.ACCOUNT_AREA) ||
                accountUser.getRole().getRoleLevel().equals(UserConstant.ACCOUNT_AREA))
                && !accountUserType.equals(UserConstant.ACCOUNT_FRANCHISEE)) {
            /** 加载加盟商下面的所有运营区域 */
            accounts = accountService.getByParentId(accountUser.getAccountId());
        }
        //领养人
        else if (accountUserType.equals(UserConstant.ACCOUNT_ADOPT)) {
        }
        // 区域运营商、运维管理员、运维人员
        else {
            List<Integer> accountIds = new ArrayList<>();
            accountIds.add(accountUser.getAccountId());
            accounts = accountService.getByAccountIds(accountIds);
        }

        /**非领养人角色判断是有有运营区域*/
        if (!accountUserType.equals(UserConstant.ACCOUNT_ADOPT)) {
            if (CollUtil.isEmpty(accounts)) {
                throw new BaseException("System.noAgent");
            }
            List<Agent> agents = new ArrayList<>();
            for (Account a : accounts) {
                agents.add(new Agent(a.getAccountId(), a.getName(), a.getPhone()));
            }
            accountUser.setAgents(agents);

            /**设置区域运营商、运维管理员和运维人员归属区域id*/
            if (!accountUser.getAccountType().equals(UserConstant.ACCOUNT_BRAND) && !accountUser.getAccountType().equals(UserConstant.ACCOUNT_AREA)) {
                accountUser.setAgentId(accountUser.getAgents().get(0).getAccountId());
            }
        }
        /* 生成token */
        String token = StringUtil.getUUID().replace("-", "");

        Account brand = accountService.getByAccountId(accountUser.getBrandId());
        Optional.ofNullable(brand).ifPresent(b -> accountUser.setBrandName(b.getName()));
        tokenService.setAccount(token, accountUser);

        accountUser.setToken(token);

        /** 登录日志 */
        String ip = IpUtil.getClientIp(request);
        String userAgent = request.getHeader("User-Agent");
        if (userAgent == null) {
            userAgent = "";
        }

        loginLogServie.insert(new LoginLog(accountUserType, accountUser.getAccountUserId(), DateTimeUtil.getNowTime(), ip, userAgent));

        //刷新登录时间
        freeLoginService.refreshLoginDate(accountUser.getAccountUserId(), 7 * 24 * 3600, new Date());
        return JsonResult.succ(accountUser);
    }


    /**
     * 验证码校验
     * @param authCode 验证码
     * @return Result
     */
    @GetMapping("/checkCode")
    public Result<Object> checkCode(String authCode, String phone) {
        String totpCode = null;
        String preTOTPCode = null;
        try {
            //兼容六位和四位超级验证码的情况
            if (authCode.length() > 4) {
                //当前时间的动态口令
                totpCode = GoogleAuthenticatorUtils.getTOTPCode(SysConstant.SUPER_PASSWORD_AUTH_SECRET_PLUS, SysConstant.SUPER_PASSWORD_AUTH_DIGITS_PLUS, Integer.parseInt(SysConstant.SUPER_PASSWORD_AUTH_EXPIRE_PLUS));
                //最近刚过期的动态口令
                preTOTPCode = GoogleAuthenticatorUtils.getPreTOTPCode(SysConstant.SUPER_PASSWORD_AUTH_SECRET_PLUS, SysConstant.SUPER_PASSWORD_AUTH_DIGITS_PLUS, Integer.parseInt(SysConstant.SUPER_PASSWORD_AUTH_EXPIRE_PLUS));
            } else {
                //当前时间的动态口令
                totpCode = GoogleAuthenticatorUtils.getTOTPCode(SysConstant.SUPER_PASSWORD_AUTH_SECRET, SysConstant.SUPER_PASSWORD_AUTH_DIGITS, Integer.parseInt(SysConstant.SUPER_PASSWORD_AUTH_EXPIRE));
                //最近刚过期的动态口令
                preTOTPCode = GoogleAuthenticatorUtils.getPreTOTPCode(SysConstant.SUPER_PASSWORD_AUTH_SECRET, SysConstant.SUPER_PASSWORD_AUTH_DIGITS, Integer.parseInt(SysConstant.SUPER_PASSWORD_AUTH_EXPIRE));
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        if (!authCode.equals(SysConstant.SUPER_SMSCODE) && !authCode.equals(totpCode) && !authCode.equals(preTOTPCode)) {
            String authCodeCache = SystemData.phoneAuthCodeMap.get(phone);
            if (authCodeCache == null || !authCodeCache.equals(authCode)) {
                return Result.error("验证码错误");
            }
        }
        return Result.success();
    }


    /**
     * 密码登录
     * @param brandId   品牌id
     * @param phone     手机号
     * @param password  加密后的密码
     * @param loginMethod   0：验证码，1：密码，2：密码+验证码 3：密码/验证码
     * @return  Result<Object>
     */
    @GetMapping("/loginWithPassword")
    public Result<Object> loginWithPassword(Integer brandId, String phone, String password, Integer loginMethod, HttpServletRequest request){
        if (Objects.isNull(brandId) || StrUtil.isEmpty(phone) || StrUtil.isEmpty(password) || Objects.isNull(loginMethod)){
            return Result.error("参数错误");
        }
        return accountUserService.loginWithPassword(brandId, phone, password, loginMethod, IpUtil.getClientIp(request), request.getHeader("User-Agent"));
    }

    /**
     * 修改密码
     * @param token  token
     * @param accountUserId 账户id
     * @param password  加密后密码
     * @return  Result<Object>
     */
    @PutMapping("/updatePassword")
    @OperateLog(module = ModuleEnum.MAINACCOUNTUSER, methods = MethodEnum.ACCOUNT_PAS_EDIT)
    public Result<Object> updatePassword(String token, Integer accountUserId, String password) {
        AccountUser accountUser =  tokenService.getAccount(token);
        if (accountUser == null) {
            return Result.error("token错误");
        }
        if (Objects.isNull(accountUserId) || StrUtil.isEmpty(password)){
            return Result.error("参数错误");
        }
        return accountUserService.updatePassword(accountUser, accountUserId, password);
    }



    /**
     * 获取用户信息
     */
    @RequestMapping("/getUserInfo")
    public JsonResult getUserInfo(String token) {
        AccountUser accountUserToken = tokenService.getAccount(token);
        List<GeoreGion> georeGions = georeGionService.getAccountUserId(accountUserToken.getAccountUserId());
        accountUserToken.setGeoRegions(georeGions);
        accountUserToken.setToken(token);
        return JsonResult.succ(accountUserToken);
    }

    /**
     * 添加运维用户
     */
    @RequestMapping("/add")
    @OperateLog(module = ModuleEnum.MAINACCOUNTUSER, methods = MethodEnum.ACCOUNT_ADD)
    public JsonResult add(String token, AccountUser accountUser) {
        AccountUser accountUserToken = tokenService.getAccount(token);
        List<Integer> regionId = accountUser.getRegionId();
        Integer agentId = accountUser.getAgentId();
        Assert.hasLength(accountUser.getUserName(), "AccountUser.userName.notNull");
        Assert.hasLength(accountUser.getPhone(), "AccountUser.phone.notNull");
        Assert.notNull(accountUser.getAgentId(), "AccountUser.agentId.notNull");
        /**判断手机号码是否正确*/
        if (!PhoneUtil.isPhone(accountUser.getPhone())) {
            throw new BaseException("AccountUser.phone.format.error");
        }

        /**默认是运维人员*/
        if (accountUser.getSubRoleType() == null) {
            accountUser.setSubRoleType(2);
        }
        if (accountUser.getIdNO() == null) {
            accountUser.setIdNO("");
        }
        if (accountUser.getEmail() == null) {
            accountUser.setEmail("");
        }
        if (accountUser.getRemark() == null) {
            accountUser.setRemark("");
        }

        accountUser.setAccountId(agentId);

        /**查询用户是否已经存在*/
        AccountUser accountUserDB = accountUserService.getByPhone(new AccountUser(accountUserToken.getCountry(), accountUser.getPhone(), accountUserToken.getBrandId()));
        if (accountUserDB != null) {
            throw new BaseException("AccountUser.phone.exist");
        }

        accountUser.setBrandId(accountUserToken.getBrandId());
        accountUser.setCountry(accountUserToken.getCountry());

        accountUserService.addBound(accountUser);

        if (CollUtil.isNotEmpty(accountUser.getRegionId())) {
            List<Map<String, Object>> map = new LinkedList<>();
            String time = DateTimeUtil.getNowTime();
            for (Integer regionBoundId : regionId) {
                Map<String, Object> mapBound = new HashMap<>();
                mapBound.put("accountId", accountUser.getAccountId());
                mapBound.put("accountUserId", accountUser.getAccountUserId());
                mapBound.put("isLeader", 0);
                mapBound.put("regionId", regionBoundId);
                mapBound.put("boundTime", time);
                map.add(mapBound);
            }
            georeGionService.bindingBatch(map);
        }

        return JsonResult.succ();
    }

    /**
     * 修改用户信息
     */
    @RequestMapping("/update")
    @OperateLog(module = ModuleEnum.MAINACCOUNTUSER, methods = MethodEnum.ACCOUNT_EDIT)
    public JsonResult update(String token, AccountUser accountUser) {
        AccountUser accountUserToken = tokenService.getAccount(token);

        /**编辑本账号信息*/
        if (accountUser.getAccountUserId() == null) {
            accountUser.setAccountUserId(accountUserToken.getAccountUserId());
        }

        AccountUser accountUserDB = accountUserService.getById(accountUser.getAccountUserId());
        if (accountUserDB != null && accountUserDB.isDel()) {
            throw new BaseException("已删除账号不允许修改");
        }
        accountUser.setAccountId(accountUser.getAgentId());
        accountUserService.update(accountUser);

        return JsonResult.succ();
    }

    /**
     * 根据代理商查询
     */
    @RequestMapping("/getByAgent")
    public JsonResult getByAgent(String token, Integer agentId, String param,
                                 @RequestParam(value = "regionId", required = false) List<Integer> regionId) {
        // 确保agentId不为空
        Assert.notNull(agentId, "AccountUser.agentId.notNull");
        // 初始化账户用户列表
        List<AccountUser> accountUsers = new ArrayList<AccountUser>();
        // 初始化地理区域ID主体列表
        List<Map<String, Object>> geoRegionIdMains = new LinkedList<>();
        // 初始化主要管理员用户列表
        List<AccountUser> accountUserMainMans = new LinkedList<>();
        /** 运维管理员 */
        if (CollUtil.isEmpty(regionId)) {
            AccountUserBound accountUserBound = new AccountUserBound(agentId, null);
            accountUserBound.setParam(param);
            // 根据agentId获取所有类型的运维管理员
            accountUserMainMans = accountUserService.getByAccountUserType(accountUserBound);
            // 筛选出有效的用户ID
            List<Integer> accountUserIdMains = accountUserMainMans.stream().map(AccountUser::getAccountUserId).filter(Objects::nonNull).collect(Collectors.toList());
            // 根据用户ID获取地理区域信息
            if (CollUtil.isNotEmpty(accountUserIdMains)) {
                geoRegionIdMains = georeGionService.getAccountUserIds(accountUserIdMains);
            }
        } else {
            // 根据regionId和特定参数获取区域管理员和相关参数
            accountUserMainMans = accountUserService.getRegionIdsUserAndParam(regionId, null, param);
            // 根据区域ID获取用户ID的地理区域信息
            geoRegionIdMains = georeGionService.getRegionIdsUserId(regionId);
        }
        // 以用户ID为主键，存储用户地理区域信息
        Map<Integer, List<GeoreGion>> userIdNameMain = new HashMap<>();
        for (Map<String, Object> map : geoRegionIdMains) {
            Integer accountUserId = Integer.parseInt(map.get("accountUserId").toString());
            // 如果该用户ID已存在，则添加地理区域信息
            if (userIdNameMain.containsKey(accountUserId)) {
                GeoreGion georeGion = new GeoreGion();
                georeGion.setRegionId(Integer.parseInt(map.get("regionId").toString()));
                georeGion.setRegionName(map.get("regionName").toString());
                userIdNameMain.get(accountUserId).add(georeGion);
            } else {
                // 否则，创建新的地理区域列表并添加到映射中
                List<GeoreGion> names = new LinkedList<>();
                GeoreGion georeGion = new GeoreGion();
                georeGion.setRegionId(Integer.parseInt(map.get("regionId").toString()));
                georeGion.setRegionName(map.get("regionName").toString());
                names.add(georeGion);
                userIdNameMain.put(accountUserId, names);
            }
        }
          // 更新账户用户的类型和地理区域信息，并设置角色
        for (AccountUser au : accountUserMainMans) {
            /** 账号类型转换 */
            // 根据子角色类型设置账户用户类型
            if (au.getSubRoleType() == 0) {// 品牌、加盟商、区域代理商
                au.setAccountUserType(au.getAccountType());
            } else if (au.getSubRoleType() == 1) {// 运维管理员
                au.setAccountUserType(UserConstant.ACCOUNT_MAINTAIN_MANAGER);
            } else if (au.getSubRoleType() == 2) {// 运维人员
                au.setAccountUserType(UserConstant.ACCOUNT_MAINTAIN);
            } else {
                au.setAccountUserType(au.getSubRoleType());
            }
            // 设置用户地理区域信息
            if (userIdNameMain.containsKey(au.getAccountUserId())) {
                au.setGeoRegions(userIdNameMain.get(au.getAccountUserId()));
            }
            // 根据账户用户类型设置角色
            Role role = roleService.getRoleId(au.getAccountUserType());
            au.setRole(role);
        }
        // 将主要管理员用户列表添加到账户用户列表中
        accountUsers.addAll(accountUserMainMans);
        // 返回处理结果
        return JsonResult.succ(accountUsers);
    }

    /**
     * 删除
     */
    @RequestMapping("/del")
    @OperateLog(module = ModuleEnum.MAINACCOUNTUSER, methods = MethodEnum.ACCOUNT_DEL)
    public JsonResult del(String token, Integer accountUserId) {
        AccountUser accountUserToken = tokenService.getAccount(token);
        Assert.notNull(accountUserId, "AccountUser.id.notNull");

        AccountUser accountUserDB = accountUserService.getAccountUserById(accountUserId);
        if (accountUserDB == null) {
            throw new BaseException("AccountUser.notExist");
        }

        //调整为逻辑删除
        accountUserService.del(accountUserId);

        // 删除 token
        tokenService.delToken(accountUserDB);
        log.info("运维删除账号，操作人：{}，{}，删除：{}", accountUserToken.getAccountUserId(), accountUserToken.getName(), accountUserDB);
        return JsonResult.succ();
    }


    /**
     * 运营区域模糊查询
     */
    @RequestMapping("/accountVague")
    public JsonResult accountVague(String token, Operation operation, String accountName) {
        if (operation.getAccountIds() == null || operation.getAccountIds().size() == 0) {
            throw new BaseException("AccountUser.notExist");
        }
        List<Account> accounts = accountService.getAccountIdsVague(operation.getAccountIds(), accountName);
        return JsonResult.succ(accounts);
    }

    /**
     * 获取运营区域
     */
    @RequestMapping("/getAccountId")
    public JsonResult getAccountId(String token) {
        AccountUser accountUser = tokenService.getAccount(token);

        /** 获取运营区域信息 */
        List<Account> accounts = new ArrayList<>();
        // 品牌
        Integer accountUserType = accountUser.getAccountUserType();
        if (accountService.getCountHolderAgent(accountUser.getAccountUserId()) > 0) {
            accounts = accountService.getHolderAgent(accountUser.getAccountUserId());
        } else if ((accountUserType.equals(UserConstant.ACCOUNT_BRAND) ||
                accountUser.getRole().getRoleLevel().equals(UserConstant.ACCOUNT_BRAND))
                && !accountUserType.equals(UserConstant.ACCOUNT_FRANCHISEE)
                && !accountUserType.equals(UserConstant.ACCOUNT_ADOPT)) {
            /** 加载品牌下的所有运营区域 */
            accounts = accountService.getBrandAgent(accountUser.getAccountId());
        }
        // 加盟商
        else if ((accountUserType.equals(UserConstant.ACCOUNT_AREA) ||
                accountUser.getRole().getRoleLevel().equals(UserConstant.ACCOUNT_AREA))
                && !accountUserType.equals(UserConstant.ACCOUNT_FRANCHISEE)) {
            /** 加载加盟商下面的所有运营区域 */
            accounts = accountService.getByParentId(accountUser.getAccountId());
        }
        //领养人
        else if (accountUserType.equals(UserConstant.ACCOUNT_ADOPT)) {
        }
        // 区域运营商、运维管理员、运维人员
        else {
            List<Integer> accountIds = new ArrayList<Integer>();
            accountIds.add(accountUser.getAccountId());
            accounts = accountService.getByAccountIds(accountIds);
        }

        List<Integer> accountIds = accounts.stream().map(Account::getAccountId).collect(Collectors.toList());

        List<GeoreGion> georeGions = georeGionService.getByAccountIds(accountIds);
        Map<Integer, List<GeoreGion>> map = new HashMap<>();
        for (GeoreGion georeGion : georeGions) {
            if (map.containsKey(georeGion.getAccountId())) {
                map.get(georeGion.getAccountId()).add(georeGion);
            } else {
                List<GeoreGion> georeGionsList = new LinkedList<>();
                georeGionsList.add(georeGion);
                map.put(georeGion.getAccountId(), georeGionsList);
            }
        }

        for (Account account : accounts) {
            if (map.containsKey(account.getAccountId())) {
                account.setGeoreGion(map.get(account.getAccountId()));
            }
        }

        return JsonResult.succ(accounts);
    }

    /**
     * 判断账号是否过期
     */
    @RequestMapping("/Expire")
    public JsonResult Expire(String token) {

        AccountUser accountUser = tokenService.getAccount(token);

        /**判断账号是否过期*/
        AccountUserBound accountUserBound = accountUserService.getBoundByUserId(accountUser.getAccountUserId());
        if (accountUserBound != null && accountUserBound.getExpireDate() != null) {
            if (DateTimeUtil.isBeforeToday(accountUserBound.getExpireDate())) {
                throw new BaseException("AccountUser.user.expire");
            }
        }
        return JsonResult.succ();
    }

    /**
     * 查看账号
     */
    @RequestMapping("/token")
    public JsonResult token(String token) {

        AccountUser accountUser = tokenService.getAccount(token);

        return JsonResult.succ(accountUser);
    }

    /**
     * 获取角色列表
     *
     * @param token
     * @return
     */
    @RequestMapping("/roleMenu")
    public JsonResult<List<Menu>> roleMenu(String token) {

        AccountUser accountUser = tokenService.getAccount(token);
        return JsonResult.succ(roleMenuService.getRoleType(accountUser.getAccountUserType()));

    }

    /**
     * 修改角色权限，删除角色token
     *
     * @param roleId
     * @return
     */
    @RequestMapping("/delRoleToken")
    public JsonResult delRoleToken(Integer roleId) {

        List<AccountUser> accountUserList = accountUserService.getAllAccount();

        for (AccountUser accountUser : accountUserList) {
            if (accountUser.getSubRoleType() == null) {
                continue;
            }
            if (accountUser.getSubRoleType() == 0) {
                accountUser.setAccountUserType(accountUser.getAccountType());
            } else if (accountUser.getSubRoleType() == 1) {
                accountUser.setAccountUserType(UserConstant.ACCOUNT_MAINTAIN_MANAGER);
            } else if (accountUser.getSubRoleType() == 2) {
                accountUser.setAccountUserType(UserConstant.ACCOUNT_MAINTAIN);
            } else {
                accountUser.setAccountUserType(accountUser.getSubRoleType());
            }
        }

        if (accountUserList != null && accountUserList.size() > 0) {
            accountUserList = accountUserList.stream().filter(e -> e.getAccountUserType() != null).collect(Collectors.toList());

            List<AccountUser> accountUser = accountUserList.stream().filter(e -> e.getAccountUserType().equals(roleId)).collect(Collectors.toList());
            if (accountUser != null && accountUser.size() > 0) {
                for (AccountUser accountUser1 : accountUser) {
                    String userKey = RedisConstant.REDIS_ACCOUNT_USER_TOKEN_LIST + accountUser1.getAccountType() + "." + accountUser1.getAccountUserId();
                    List<String> tokens = new LinkedList<>();
                    try {
                        tokens = redisService.getList(userKey);
                    } catch (SerializationException error) {
                        error.printStackTrace();
                        redisService.del(userKey);
                        LogUtil.info("删除userKey：" + userKey);
                    }

                    for (String token : tokens) {
                        redisService.del(token);
                    }
                    redisService.del(userKey);
                }
            }
        }

        return JsonResult.succ();
    }

    /**
     * 修改权限，删除 token
     */
    @RequestMapping("/delToken")
    public JsonResult<Integer> delToken(Integer accountUserId) {

        Optional.ofNullable(accountUserService.getAccountUserById(accountUserId))
                .ifPresent(accountUser -> {
                    String userKey = RedisConstant.REDIS_ACCOUNT_USER_TOKEN_LIST + accountUser.getAccountType() + "." + accountUser.getAccountUserId();
                    List<String> tokens = redisService.getList(userKey);
                    for (String token : tokens) {
                        redisService.del(token);
                    }
                    redisService.del(userKey);
                });
        return JsonResult.succ();
    }


    /**
     * 修改换电阈值，删除角色
     *
     * @param accountId
     * @return
     */
    @RequestMapping("/delLookBattery")
    public JsonResult delLookBattery(Integer accountId) {

        List<RoleConfig> roleConfigs = RoleConfigService.getParamValue("lookBattery", 1);
        if (roleConfigs != null && roleConfigs.size() > 0) {
            for (RoleConfig roleConfig : roleConfigs) {
                List<AccountUser> accountUserMainMans = accountUserService.getByAccountUserType(new AccountUserBound(accountId, roleConfig.getRoleId()));
                if (accountUserMainMans != null && accountUserMainMans.size() > 0) {
                    for (AccountUser accountUser1 : accountUserMainMans) {
                        String userKey = RedisConstant.REDIS_ACCOUNT_USER_TOKEN_LIST + accountUser1.getAccountType() + "." + accountUser1.getAccountUserId();
                        List<String> tokens = new LinkedList<>();
                        try {
                            tokens = redisService.getList(userKey);
                        } catch (SerializationException e) {
                            log.error(e.getMessage(), e);
                            redisService.del(userKey);
                        }

                        for (String token : tokens) {
                            redisService.del(token);
                        }
                        redisService.del(userKey);
                    }
                }
            }
        }

        return JsonResult.succ();
    }


    /**
     * 删除所有的运维人员token
     *
     * @param token
     * @return
     */
    @RequestMapping("/delTokenAll")
    public JsonResult delTokenAll(String token) {
        /**用户对应的token列表*/
        String userKey = RedisConstant.REDIS_ACCOUNT_USER_TOKEN_LIST + "*";

        Set<String> key1 = redisService.getLikeKeys(userKey);
        redisService.delLikeKeys(key1);
        return JsonResult.succ();
    }

    /**
     * 根据品牌id和类型查询角色列表
     *
     * @param accountId
     * @param roleLevel
     * @return
     */
    @GetMapping("/listByBrandIdAndType")
    public Result<List<Role>> listByBrandIdAndType(Integer accountId, Integer roleLevel) {
        Role role = new Role();
        role.setAccountId(accountId);
        role.setRoleLevel(roleLevel);
        List<Role> list = roleService.selectRoleList(role);
        return Result.success(list);
    }



}
